#include "wave.h"

static void     fifo_push(s_object *object, e_enn type, int life, int delay)
{
    s_fifo  *new;
    s_fifo  *cur = object->fifo;

    new = malloc(sizeof (s_fifo));

    while (cur && cur->next)
        cur = cur->next;

    new->type = type;
    new->life = life;
    new->delay = delay;
    new->next = NULL;

    if (cur)
        cur->next = new;
    else
        object->fifo = new;
}

static s_fifo   *fifo_pop(s_object *object)
{
    s_fifo *f = object->fifo;

    if (!f)
        return (NULL);

    object->fifo = f->next;

    return (f);
}

int             init_wave(s_object *object)
{
    char    file[64];
    FILE    *stream = NULL;
    int     i = 0;
    int     type = 0;
    int     life = 0;
    int     delay = 0;
    char    line[64];

    sprintf(file, "../check/waves/%d", object->wave);
    if (!(stream = fopen(file, "r")))
    {
        fprintf(stderr, "[!] Wave file non-existing\n");
        return (0);
    }
    fprintf(stderr, "[!!] Wave n° %d\n", object->wave);
    while (fgets(line, 64, stream))
    {
        type = (i % 3 == 0) ? atoi(line) : type;
        life = (i % 3 == 1) ? atoi(line) : life;
        delay = (i % 3 == 2) ? atoi(line) : delay;
        if (i != 0 && i % 3 == 0)
            fifo_push(object, type, life, delay);
        i++;
    }
    fclose(stream);
    return (1);
}

int launch_new_enn(s_object *object, int *delay)
{
    s_fifo *enn = NULL;

    if (!*delay && object->enn_list != NULL)
        return (1);

    if (!*delay)
    {
        object->wave += 1;
        if (!init_wave(object))
        {
            fprintf(stderr, "[!!] Victory !\n");
            return (0);
        }
    }

    enn = fifo_pop(object);
    if (enn)
    {
        add_to_enn_list(enn->type, object);
        *delay = enn->delay;
    }
    else
        *delay = 0;

    return (1);
}

void update_wave(s_object *object, int time[3])
{

    if ((time[0] = SDL_GetTicks()) && time[0] - time[2] > 200)
    {
        if (time[0] % 2 == 0)
            check_collide(object);
        update_all_pos(object);
        draw(object);
        time[2] = time[0];
    }
}
